const { DataTypes } = require('sequelize')
const { sequelize } = require('../config/database')

const User = sequelize.define('User', {
  id: {
    type: DataTypes.STRING(50),
    primaryKey: true,
    allowNull: false
  },
  username: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true
  },
  email: {
    type: DataTypes.STRING(255),
    allowNull: false,
    unique: true,
    validate: {
      isEmail: true
    }
  },
  password: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  role: {
    type: DataTypes.ENUM('admin', 'student', 'teacher'),
    allowNull: false,
    defaultValue: 'student'
  },
  firstName: {
    type: DataTypes.STRING(100),
    allowNull: true
  },
  lastName: {
    type: DataTypes.STRING(100),
    allowNull: true
  },
  avatar: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  phone: {
    type: DataTypes.STRING(20),
    allowNull: true
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    defaultValue: true
  },
  lastLoginAt: {
    type: DataTypes.DATE,
    allowNull: true
  }
}, {
  tableName: 'users',
  timestamps: true,
  createdAt: 'createdAt',
  updatedAt: 'updatedAt',
  indexes: [
    {
      unique: true,
      fields: ['username']
    },
    {
      unique: true,
      fields: ['email']
    },
    {
      fields: ['role']
    }
  ]
})

// 添加静态方法
User.sanitizeUser = function(user) {
  if (!user) return null
  
  const sanitized = user.toJSON ? user.toJSON() : user
  delete sanitized.password
  return sanitized
}

// 检查用户是否为管理员
User.isAdmin = function(user) {
  return user && user.role === 'admin'
}

// 检查用户是否有指定角色权限
User.hasPermission = function(user, requiredRole) {
  if (!user || !user.role) {
    return false
  }
  
  // 角色权限层级：admin > teacher > student
  const roleHierarchy = {
    'admin': 3,
    'teacher': 2,
    'student': 1
  }
  
  const userLevel = roleHierarchy[user.role] || 0
  const requiredLevel = roleHierarchy[requiredRole] || 0
  
  return userLevel >= requiredLevel
}

module.exports = User